package com.xianggu.spring.transaction.context;

import com.xianggu.mybatis.mysql.DruidExample;

import java.sql.Connection;
import java.sql.SQLException;

public class TransactionContext {

    private static final ThreadLocal<Connection> CONNECTION_HOLDER = new ThreadLocal<>();

    public static void setConnection(Connection connection) {
        CONNECTION_HOLDER.set(connection);
    }

    public static Connection getConnection() {
        Connection connection = CONNECTION_HOLDER.get();
        if (connection == null) {
            // 如果当前线程没有绑定Connection，则从连接池获取一个
            try {
                connection = DruidExample.getConnection();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            // 绑定到当前线程
            setConnection(connection);
        }
        return connection;
    }

    public static void removeConnection() {
        CONNECTION_HOLDER.remove();
    }
}